<script setup lang="tsx">
import { Search } from '@/components/Search'
import { ContentWrap } from '@/components/ContentWrap'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { permissionTableColumns, permissionFormRules } from './components/data'
import { ref, unref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useTable } from '@/hooks/web/useTable'
import {
  adminPermissionList,
  adminPermissionDelete,
  adminPermissionUpdate,
  adminPermissionCreate,
  adminPermissionAncestors
} from '@/api/rest/permission'
import { useI18n } from '@/hooks/web/useI18n'
import { TableData } from '@/api/table/types'
import { ElButton, ElRow, ElCol, ElBreadcrumb, ElBreadcrumbItem } from 'element-plus'
import Write from '@/views/rest/components/dialog/Write.vue'
import Detail from '@/views/rest/components/dialog/Detail.vue'
import { Table } from '@/components/Table'
import { Dialog } from '@/components/Dialog'
import { useIcon } from '@/hooks/web/useIcon'
const { push } = useRouter()
const route = useRoute()
const addIcon = useIcon({ icon: 'ep:plus' })
const ids = ref<string[]>([])

const ancestors = ref<any[]>([])

let parentId = ref('0')
parentId.value = (route.query.parentId as string) || '0'
const searchParams = ref({
  parentId: parentId.value
})

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res = await adminPermissionList({
      page: unref(currentPage),
      limit: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: res.data.items,
      total: res.data.total
    }
  },
  fetchDelApi: async () => {
    const res = await adminPermissionDelete(unref(ids))
    return !!res
  }
})
const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList, getElTableExpose, delList } = tableMethods

onMounted(() => {
  adminPermissionAncestors(parentId.value).then((res) => {
    ancestors.value = res.data
  })
})

// watch(
//   () => route.query,
//   () => {
//     //console.log('--------')
//     parentId.value = (route.query.parentId as string) || '0'
//     searchParams.value.parentId = parentId.value
//     adminPermissionAncestors(parentId.value).then((res) => {
//       ancestors.value = res.data
//     })
//     getList()
//   }
// )

const { t } = useI18n()

const setSearchParams = (params: any) => {
  searchParams.value = params
  getList()
}

const actionColumns = reactive<CrudSchema[]>([
  {
    field: 'action',
    width: '400px',
    label: t('restCommon.action'),
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          return (
            <>
              <ElButton
                type="success"
                icon={() => useIcon({ icon: 'ep:folder-opened' })}
                onClick={() => subList(data.row.id)}
              >
                {t('restPermission.children')}
              </ElButton>
              <ElButton
                type="primary"
                icon={() => useIcon({ icon: 'ep:edit' })}
                onClick={() => action(data.row, 'edit')}
              >
                {t('restOperate.edit')}
              </ElButton>
              <ElButton
                type="success"
                icon={() => useIcon({ icon: 'ep:view' })}
                onClick={() => action(data.row, 'detail')}
              >
                {t('restOperate.detail')}
              </ElButton>
              <ElButton
                type="danger"
                icon={() => useIcon({ icon: 'ep:delete' })}
                onClick={() => delData(data.row)}
              >
                {t('restOperate.del')}
              </ElButton>
            </>
          )
        }
      }
    }
  }
])
const crudSchemas = permissionTableColumns.concat(actionColumns)
const formRules = permissionFormRules
const { allSchemas } = useCrudSchemas(crudSchemas)

const dialogVisible = ref(false)
const dialogTitle = ref('')

const currentRow = ref<TableData | null>(null)
const actionType = ref('')

const AddAction = () => {
  dialogTitle.value = t('restOperate.add')
  currentRow.value = null
  dialogVisible.value = true
  actionType.value = ''
}

const delLoading = ref(false)

const delData = async (row: TableData | null) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row ? [row.id] : elTableExpose?.getSelectionRows().map((v: TableData) => v.id) || []
  delLoading.value = true
  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}

const action = (row: TableData, type: string) => {
  dialogTitle.value = t(type === 'edit' ? 'restOperate.edit' : 'restOperate.detail')
  actionType.value = type
  currentRow.value = row
  dialogVisible.value = true
}

const subList = (id: string) => {
  push({ path: '/sys/permission/list', query: { parentId: id } })
}

const writeRef = ref<ComponentRef<typeof Write>>()

const saveLoading = ref(false)

const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    if (actionType.value === 'edit') {
      const res = await adminPermissionUpdate(formData)
      if (res) {
        dialogVisible.value = false
        //currentPage.value = 1
        saveLoading.value = false
        await getList()
      }
    } else {
      formData.parentId = parentId.value
      const res = await adminPermissionCreate(formData)
      if (res) {
        dialogVisible.value = false
        currentPage.value = 1
        saveLoading.value = false
        await getList()
      }
    }
  }
}
</script>

<template>
  <ContentWrap>
    <ElRow>
      <ElCol :span="18">
        <Search
          :schema="allSchemas.searchSchema"
          @search="setSearchParams"
          @reset="setSearchParams"
        />
      </ElCol>
      <ElCol :span="4">
        <ElRow justify="end">
          <ElButton type="primary" :icon="addIcon" @click="AddAction">{{
            t('restOperate.add')
          }}</ElButton>
        </ElRow>
      </ElCol>
    </ElRow>
    <ElRow style="margin-bottom: 20px">
      <ElCol :span="24">
        <ElBreadcrumb separator="/" style="margin-right: 10px">
          <ElBreadcrumbItem :to="{ path: '/sys/permission/list', query: { parentId: 0 } }"
            >顶层</ElBreadcrumbItem
          >
          <ElBreadcrumbItem
            v-for="item in ancestors"
            :key="item.id"
            :to="{ path: '/sys/permission/list', query: { parentId: item.id } }"
            >{{ item.name }}</ElBreadcrumbItem
          >
        </ElBreadcrumb>
      </ElCol>
    </ElRow>

    <Table
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :columns="allSchemas.tableColumns"
      :data="dataList"
      :loading="loading"
      :pagination="{
        total: total
      }"
      @register="tableRegister"
    />
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Write
      v-if="actionType !== 'detail'"
      ref="writeRef"
      :form-schema="allSchemas.formSchema"
      :current-row="currentRow"
      :form-rules="formRules"
    />

    <Detail
      v-if="actionType === 'detail'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="currentRow"
    />

    <template #footer>
      <ElButton v-if="actionType !== 'detail'" type="primary" :loading="saveLoading" @click="save">
        {{ t('exampleDemo.save') }}
      </ElButton>
      <ElButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</ElButton>
    </template>
  </Dialog>
</template>

<style scoped lang="less"></style>
